#include "Configuration.h"
#include <iostream>
#include <fstream>
#include <functional>

unique_ptr<Configuration> Configuration::instance = nullptr;
once_flag Configuration::initConfigurationFlag;

Configuration* Configuration::getInstance(const string &filepath){
    call_once(initConfigurationFlag, [filepath]{
              initConfiguration(filepath);
    });
    return instance.get();
}

void Configuration::initConfiguration(const string &filepath){
    instance.reset(new Configuration(filepath));
}

Configuration::Configuration(const string &filepath)
: _filepath(filepath){
    //读取配置文件
    ifstream ifs(_filepath);
    if(!ifs){
        cerr << "Unable to open config file: " << _filepath << "\n";
        return;
    }
    string line;
    while(getline(ifs, line)){
        size_t pos = line.find('=');
        if(pos != string::npos){
            string label = line.substr(0, pos);
            string info = line.substr(pos + 1);
            _configMap[label] = info;
        }
    }
    cout << "配置文件读取成功\n";
    
    //读取停用词词集
    string stopPath = _configMap["STOP_WORD_PATH"];
    ifstream ifs2(stopPath);
    if(!ifs2){
        cerr << "Unable to open config file: " << _filepath << "\n";
        return;
    }
    string word;
    while(ifs2 >> word){
        _stopWordList.insert(word);
    }
    cout << "停用词词集读取成功\n";
}

Configuration::~Configuration(){

}

//获取存放配置文件内容的map
map<string, string> &Configuration::getConfigMap(){
    return _configMap;
}

//根据配置名找到对应内容
string Configuration::parseConfig(const string &label){
    if(_configMap.count(label) == 0){
        cout << "Can't find this tag" << endl;
        return string();
    }
    return _configMap[label];
}

//获取停用词词集
set<string> &Configuration::getStopWordList(){
    return _stopWordList;
}

//打印配置文件
void Configuration::printConfigMap(){
    for(const auto &i: _configMap){
        cout << i.first << " = " << i.second << "\n";
    }
}

//打印停用词词集
void Configuration::printStopWordList(){
    for(const auto &i: _stopWordList){
        cout << i << "\n";
    }
}
